<?php
/*
+-----------------------------------------------------------------------------+
| $Id: register.php 2010-05-24 12:37:44Z Bleakwind $
| Member register
| Copyright (c) 2003-2010 Bleakwind (www.weaverdream.com)
| http://www.weaverdream.com/
| Release under the GNU Lesser General Public License Version 3 (LGPLv3):
|   http://www.gnu.org/licenses/lgpl.html
+-----------------------------------------------------------------------------+
*/

if (!defined( 'ENTRY_INDEX')){
    echo "<h1>Forbidden</h1><p>You don't have permission to access on this server.</p>";
    exit;
}

function question_select($id, $select, $value)
{
    global $LANGUAGE,$LANGLIST,$SETTING,$sys, $member_info;
    $ajax_response = new xajaxResponse();
    if ( $value == "custom"){
        $ajax_response->assign($select, "style.width", '80px');
        $ajax_response->assign($id, "style.display", 'inline');
    } else {
        $ajax_response->assign($select, "style.width", '320px');
        $ajax_response->assign($id, "style.display", 'none');
    }
    return $ajax_response;
}
$bwajax->register(XAJAX_FUNCTION, "question_select");

function register_member($value)
{
    global $SETTING,$LANGUAGE,$CONFIG,$CONFIGURE,$SESSION,$PROMPT,$LANGLIST,$db,$sys,$c;
    $ajax_response = new xajaxResponse();
    $error = false;
    //$ajax_response->alert(print_r($value, true)); $ajax_response->assign($submit,"disabled",false); return $ajax_response;
    //func::fp($value);

    $value['username'] = strtolower(trim($value['username']));
    if (!empty($CONFIG['censor_username'])) {
        if (mb_eregi("^(".implode("|", preg_split("/[\s,]+/", str_replace("*", ".*", str_replace("\*", "*", quotemeta($CONFIG['censor_username']))))).")$", $value['username'])) {
            $error = true;
            if(empty($anchor)) { $anchor = "username"; }
            $ajax_response->assign("username_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['censor_username']."</span>");
        }
    }
    if ($error != true) {
        if ( mb_strwidth($value['username'],"UTF-8") < 4 ||
             mb_strwidth($value['username'],"UTF-8") > 60 ||
             preg_match("/[\x01-\x2E]|[\\x2F]|[\x3A-\x40]|[\x5B-\x5E]|[\x60]|[\x7B-\x7F]/",$value['username']) ) {
             //}elseif( !preg_match("/^[^\$\=\&\*\#\"\<\>\{\}]+$/",$value['username']) ){
            $error = true;
            if(empty($anchor)) { $anchor = "username"; }
            $ajax_response->assign("username_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_username_error']."</span>");
        }else{
            $sql = "SELECT id FROM ".DB_TABLE_MEMBER." WHERE username='".$value['username']."'";
            $result = &$db->Execute($sql);
            if ($result->RecordCount() > 0) {
                $error = true;
                if(empty($anchor)) { $anchor = "username"; }
                $suffix = rand(100,999);
                $ajax_response->assign("username_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_username_alreadyuse']."
                    <br><input type=\"radio\" name=\"select_username\" onclick=\"xajax.$('username').value='".$value['username'].date("Y")."';\">".$value['username'].date("Y")."
                    <br><input type=\"radio\" name=\"select_username\" onclick=\"xajax.$('username').value='".$value['username']."1"."';\">".$value['username']."1"."
                    <br><input type=\"radio\" name=\"select_username\" onclick=\"xajax.$('username').value='".$value['username'].$suffix."';\">".$value['username'].$suffix."
                    </span>");
            } else {
                $ajax_response->assign("username_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_username_right']."</span>");
            }
        }
    }

    $value['email'] = strtolower($value['email']);
    if ( !preg_match("/^[a-z0-9-_\.]+@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,4}$/i",$value['email']) ) {
        $error = true;
        if(empty($anchor)) { $anchor = "email"; }
        $ajax_response->assign("email_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_email_error']."</span>");
    } else {
        $sql = "SELECT id FROM ".DB_TABLE_MEMBER." WHERE email='".$value['email']."'";
        $result = &$db->Execute($sql);
        if ($result->RecordCount() > 0 && $value['email'] != "bleakwind@gmail.com") {
            $error = true;
            if(empty($anchor)) { $anchor = "email"; }
            $ajax_response->assign("email_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_email_alreadyuse']."</span>");
        } else {
            $ajax_response->assign("email_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_email_right']."</span>");
        }
    }

    if ( mb_strwidth($value['password1'],"UTF-8") < 6 ||
        mb_strwidth($value['password1'],"UTF-8") > 60 ){
        $error = true;
        if(empty($anchor)) { $anchor = "password1"; }
        $ajax_response->assign("password1_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_password1_error']."</span>");
    } else {
        $ajax_response->assign("password1_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_password1_right']."</span>");
    }

    if ( mb_strwidth($value['password2'],"UTF-8") < 6 ||
        mb_strwidth($value['password2'],"UTF-8") > 60 ||
        $value['password2'] != $value['password1']){
        $error = true;
        if(empty($anchor)) { $anchor = "password2"; }
        $ajax_response->assign("password2_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_password2_error']."</span>");
    } else {
        $ajax_response->assign("password2_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_password2_right']."</span>");
    }

    $question_type = "1";
    if( !preg_match("/^[1-9][0-9]{0,10}$/",$value['question']) && $value['question'] != "custom" ){
        $error = true;
        if(empty($anchor)) { $anchor = "question"; }
        $ajax_response->assign("question_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_question_error']."</span>");
    } elseif ($value['question'] == "custom") {
        if ( mb_strwidth($value['question_custom'],"UTF-8") < 6 ||
            mb_strwidth($value['question_custom'],"UTF-8") > 30 ) {
            $error = true;
            if(empty($anchor)) { $anchor = "question"; }
            $ajax_response->assign("question_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_question_custom_error']."</span>");
        } else {
            $question_type = "2";
            $question = $value['question_custom'];
            $ajax_response->assign("question_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_question_custom_right']."</span>");
        }
    } else {
        $question_type = "1";
        $question = $value['question'];
        $ajax_response->assign("question_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_question_right']."</span>");
    }

    if ( mb_strwidth($value['answer'],"UTF-8") < 6 ||
        mb_strwidth($value['answer'],"UTF-8") > 30 ) {
        $error = true;
        if(empty($anchor)) { $anchor = "answer"; }
        $ajax_response->assign("answer_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_answer_error']."</span>");
    } else {
        $ajax_response->assign("answer_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_answer_right']."</span>");
    }

    if ( empty($value['verifycode']) || strtolower($value['verifycode']) != strtolower($SESSION->_['vc_register']) ){
        $error = true;
        if(empty($anchor)) { $anchor = "verifycode"; }
        $ajax_response->assign("verifycode_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_verifycode_error']."</span>");
        $ajax_response->script("xajax_switch_verifycode('vc_register_show','".$CONFIGURE['common']['control_index']."','vc_register');");
    } else {
        $ajax_response->assign("verifycode_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_verifycode_right']."</span>");
    }

    if ( $value['agree'] != "1" ) {
        $error = true;
        if(empty($anchor)) { $anchor = "agree"; }
        $ajax_response->assign("agree_return", "innerHTML", "<span class=\"prompt_failed\">".$LANGUAGE['s']['register']['save_agree_error']."</span>");
    } else {
        $ajax_response->assign("agree_return", "innerHTML", "<span class=\"prompt_succeed\">".$LANGUAGE['s']['register']['save_agree_right']."</span>");
    }

    if($error){
        $ajax_response->assign("register_submit","value",$LANGUAGE['s']['register']['submit_register']);
        $ajax_response->assign("register_submit","disabled",false);
        $ajax_response->redirect("#".$anchor);
    }else{

        //////
        $sql = "INSERT INTO ".DB_TABLE_MEMBER." SET
                    username                ='".addslashes($value['username'])."',
                    email                   ='".addslashes($value['email'])."',
                    card                    ='',
                    password                ='".func::str_encrypt($value['password1'],$CONFIGURE['sys']['encrypt_mix'])."',
                    question_type           =".addslashes($question_type).",
                    question                ='".addslashes($question)."',
                    answer                  ='".addslashes($value['answer'])."',
                    mg_type                 ='".$CONFIG['default_group_member']."',
                    mg_type_expired         ='0',
                    silver                  ='0.00',
                    offer                   ='0.00',
                    point                   ='0',
                    bonus                   ='0',
                    pile1                   ='0',
                    pile2                   ='0',
                    pile3                   ='0',
                    pile4                   ='0',
                    pile5                   ='0',
                    pile6                   ='0',
                    active_id               ='0',
                    if_active               ='1',
                    if_enable               ='1',
                    if_email                ='1',
                    ip_active               ='".func::return_ip()."',
                    ip_created              ='".func::return_ip()."',
                    ip_change               ='".func::return_ip()."',
                    ip_lastvisit            ='".func::return_ip()."',
                    time_active             =".$sys->nowtime.",
                    time_created            =".$sys->nowtime.",
                    time_change             =".$sys->nowtime.",
                    time_lastvisit          =".$sys->nowtime.",
                    cumulant_silver         ='0',
                    cumulant_online         ='0'";
        $result = &$db->Execute($sql);
        $last_record = $db->Insert_ID();
        if (!$result) {
            $ajax_response->alert($db->ErrorMsg());
        }else{

            $sql = "SELECT id,username,email,password FROM ".DB_TABLE_MEMBER." WHERE id='".$last_record."'";
            $result = &$db->Execute($sql);
            if (!$result) {
                $ajax_response->alert($db->ErrorMsg());
            } else {
                if ($result->RecordCount() <= 0) {
                    $msg = $LANGUAGE['s']['register']['save_login_error']."";
                    $ret = $sys->get['act'];
                    $ajax_response->redirect($CONFIGURE['common']['control_index']."?act=login&msg=".$msg."&ret=".$ret);
                }else{

                    // Front session
                    $c->set_lifetime("1800");
                    if ($value['lifetime'] == "3600" ||
                        $value['lifetime'] == "86400" ||
                        $value['lifetime'] == "604800" ||
                        $value['lifetime'] == "2592000" ||
                        $value['lifetime'] == "31536000" ) {
                        $c->set_lifetime($value['lifetime']);
                    }
                    $c->set_cookie(array(
                        $CONFIGURE['sys']['cookie_prefix']."mid"        => $result->fields['id'],
                        $CONFIGURE['sys']['cookie_prefix']."musername"  => $result->fields['username'],
                    ));
                    $c->set_session(array(
                        "mid"       => $result->fields['id'],
                        "musername" => $result->fields['username'],
                    ));

                    $mail               = new PHPMailer();
                    $mail->SetLanguage("en");

                    $mail->CharSet      = $LANGUAGE['s']['register']['mail_register_charset'];
                    $mail->WordWrap     = 60;
                    $mail->IsHTML(true);
                    $mail->IsMail();

                    $mail->From         = $CONFIG['email_from'];
                    $mail->FromName     = iconv($LANGUAGE['s']['_public']['global']['charset'], $mail->CharSet, $LANGUAGE['s']['register']['mail_register_fromname']);
                    $mail->Subject      = iconv($LANGUAGE['s']['_public']['global']['charset'], $mail->CharSet, $LANGUAGE['s']['register']['mail_register_subject']);

                    $body               = $mail->getFile('language/'.$LANGLIST[$CONFIG['language']]['dir'].'/template/mail_register_html.php');
                    //$body               = preg_replace("/\\\\/","",$body);
                    $body               = str_replace("[MAIL_USERNAME]",$result->fields['username'],$body);
                    $body               = str_replace("[MAIL_EMAIL]",$result->fields['email'],$body);
                    $body               = str_replace("[MAIL_FROMNAME]",$LANGUAGE['s']['register']['mail_fromname'],$body);
                    $body               = str_replace("[MAIL_CONFIG_ROOTDIR]",CONFIG_ROOTDIR,$body);
                    $body               = str_replace("[MAIL_CONTROL_INDEX]",$CONFIGURE['common']['control_index'],$body);
                    $body               = iconv($LANGUAGE['s']['_public']['global']['charset'], $mail->CharSet, $body);
                    $mail->MsgHTML($body);

                    $mail->AltBody      = $mail->getFile('language/'.$LANGLIST[$CONFIG['language']]['dir'].'/template/mail_register_text.php');
                    $mail->AltBody      = preg_replace("/\\\\/","",$mail->AltBody);
                    $mail->AltBody      = str_replace("[MAIL_USERNAME]",$result->fields['username'],$mail->AltBody);
                    $mail->AltBody      = str_replace("[MAIL_EMAIL]",$result->fields['email'],$mail->AltBody);
                    $mail->AltBody      = str_replace("[MAIL_FROMNAME]",$LANGUAGE['s']['register']['mail_fromname'],$mail->AltBody);
                    $mail->AltBody      = str_replace("[MAIL_CONFIG_ROOTDIR]",CONFIG_ROOTDIR,$mail->AltBody);
                    $mail->AltBody      = str_replace("[MAIL_CONTROL_INDEX]",$CONFIGURE['common']['control_index'],$mail->AltBody);
                    $mail->AltBody      = iconv($LANGUAGE['s']['_public']['global']['charset'], $mail->CharSet, $mail->AltBody);

                    $mail->AddAddress($value['email']);

                    //$ajax_response->alert(print_r($mail->FromName, true)); $ajax_response->assign("register_submit","disabled",false); return $ajax_response;

                    if(!$mail->Send()){
                        $sys->set_prompt(array(
                            "prompt_type"       => "'prompt'",
                            "prompt_if"         => "1",
                            "prompt_message"    => "'".$LANGUAGE['s']['register']['mail_register_sendfailed']."[".$mail->ErrorInfo."]'",
                            "prompt_returnurl"  => "'".$CONFIGURE['common']['control_index']."?act=cp'",
                            "prompt_returntext" => "'".$LANGUAGE['s']['register']['save_jump']."'",
                            "prompt_image"      => "'failed.gif'",
                            "prompt_act"        => "'prompt'",
                        ));
                        $ajax_response->redirect($CONFIGURE['common']['control_index']."?act=prompt");
                    }else{
                        $sys->set_prompt(array(
                            "prompt_type"       => "'prompt'",
                            "prompt_if"         => "1",
                            "prompt_message"    => "'".$LANGUAGE['s']['register']['mail_register_sendsucceed']."'",
                            "prompt_returnurl"  => "'".$CONFIGURE['common']['control_index']."?act=cp'",
                            "prompt_returntext" => "'".$LANGUAGE['s']['register']['save_jump']."'",
                            "prompt_image"      => "'succeed.gif'",
                            "prompt_act"        => "'prompt'",
                        ));
                        $ajax_response->redirect($CONFIGURE['common']['control_index']."?act=prompt");
                    }
                }
            }
        }
        //////
    }
    return $ajax_response;
}
$bwajax->register(XAJAX_FUNCTION, "register_member");

if ($CONFIG['if_register'] != "1"){
    $sys->prompt("failed",$LANGUAGE['s']['register']['if_register_close']."<!-- register close -->");
} else {
    $config_list = func::db_select(DB_TABLE_CONFIG, "name,value", "name='forum_rule' OR name='censor_username'");
    if (!empty($config_list)) {
        foreach($config_list as $v){
            $CONFIG[$v['name']] = trim($v['value']);
        }
    }
}
$public_var['page_place'][] = $LANGUAGE['s']['register']['page_place'];
?>
